package org.pku_uestc.hackathon.sensor;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.pku_uestc.hackathon.bean.ISensorHandler;
import org.pku_uestc.hackathon.bean.Sensor;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;

@SuppressLint("HandlerLeak")
public class AirQualitySensor extends Sensor {
    
    private int id;
        
    public AirQualitySensor(int id) {
    	super();
        this.id = id;
    }
    
    @Override
    public int getType() {
        return TYPE_AIRQUALITY;
    }

    @SuppressLint("HandlerLeak")
	private final Handler checkHandler = new Handler(){
    	@Override
		public void handleMessage(Message msg){
    		JSONTokener jsonParser = new JSONTokener(msg.getData().getString("RESPONSE"));  
			try {
				JSONObject data = (JSONObject) jsonParser.nextValue();
				JSONArray arry = data.getJSONArray("data_points");
				if(arry.length()>0){
					String value = ((JSONObject)arry.get(0)).getString("value");
					if(list!=null){
						for(ISensorHandler handler : list)
							handler.check(value);
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
	 			e.printStackTrace();
			}  
    	}
    };
    
    @Override
    public void request(int timer) {
    	this.preformGetRequest(checkHandler, 
    			"https://huantengsmart.com/air_quality_data/"+id+".json"
    	             +"?start=15_min_ago&auth_token="+token);
    }

	@Override
	public int getId() {
		// TODO Auto-generated method stub
		return id;
	}
}
